<?php
namespace app\common\business;

use app\common\model\mysql\Category as CategoryModel;

class Category extends BusBase
{

    public $model = null;

    public function __construct()
    {
        $this->model = new CategoryModel();
    }

    public function add($data)
    {
        if (empty($data) || !is_array($data)) {
            throw new \think\Exception('数据异常');
        }

        $data['status'] = CategoryModel::STATUS_NORMAL;

        $name = $data['name'];
        $res = $this->model->findCategoryByname($name);
        if ($res) {
            throw new \think\Exception('分类名已存在, 请重新添加');
        }

        try {
            $this->model->save($data);
        } catch (\Exception $e) {
            throw new \think\Exception('数据库内部异常');
        }
        return $this->model->id;
    }

    public function updateCategoryName($data)
    {
        if (empty($data) || !is_array($data)) {
            throw new \think\Exception('数据异常');
        }

        $data['status'] = CategoryModel::STATUS_NORMAL;

        $res = $this->getById($data['id']);
        if (!$res) {
            throw new \think\Exception('不存在该记录');
        }

        $name = $data['name'];
        $res = $this->model->findCategoryByname($name);
        if ($res) {
            throw new \think\Exception('分类名已存在, 请重新添加');
        }

        $updateData = [
            'name' => $data['name'],
        ];
        try {
            $res =  $this->model->updateById($data['id'],$updateData);
        } catch (\Exception $e) {
            throw new \think\Exception('数据库内部异常');
        }
        return $res;
    }

    public function getNormalCategorys(): array
    {
        $field = "id, name, pid";
        $categorys = $this->model->getNormalCategorys($field);
        if (!$categorys) {
            return [];
        }

        return $categorys->toArray();
    }

    public function getLists($data, $num): array
    {
        $list = $this->model->getLists($data, $num);
        if (!$list) {
            return [];
        }

        $result = $list->toArray();

        $result['render'] = $list->render();

        //获取分类有多少子分类
        $pids = array_column($result['data'],'id');
        if ($pids) {
            $idCountResult = $this->model->getChildCountInPids(['pid' => $pids]);
            $idCountResult = $idCountResult->toArray();

            $idCounts = [];
            foreach ($idCountResult as $countResult) {
                $idCounts[$countResult['pid']] = $countResult['count'];
            }
        }

        if ($result) {
            foreach($result['data'] as $k => $v) {
                $result['data'][$k]['childCount'] = $idCounts[$v['id']] ?? 0;
            }
        }

        return $result;
    }




    public function getNormalByPid($pid = 0, $field = 'id, name, pid')
    {
        try {
            $res = $this->model->getNormalByPid($pid, $field);
        } catch (\Exception $e) {
            return [];
        }
        return $res->toArray();
    }
}